import React, { useState, useEffect, useRef } from 'react'
import { Space, Modal, message, Tooltip } from 'antd';
import { ProFormDateRangePicker, ProTable } from '@ant-design/pro-components';
import TheButton from "@/components/TheButton/index.jsx";
import { QuestionCircleOutlined } from "@ant-design/icons";
import moment from 'moment';
import { useLocation, useNavigate } from "react-router-dom";
import GoBack from "@/components/TheGoBack/index.jsx";
import { apiGetSpellTogetherDashboards, apiExportDataDashboards } from "@/api/spellTogether/index.js";
import { Decimal } from 'decimal.js';
import Json2Excel from '@/utils/Json2Excel.js'

const { confirm } = Modal
export default (props) => {
  const location = useLocation();
  const actionRef = useRef();
  const [queryForm, setQueryForm] = useState()
  const [exportLoading, setExportLoading] = useState(false); // 导出loading
  const columns = [
    {
      title: "统计时间",
      dataIndex: "time",
      key: "time",
      hideInTable: true,
      renderFormItem: () => {
        return <ProFormDateRangePicker
          formItemProps={{
            className: 'form-rangePicker-w',
          }}
        />
      },
      search: {
        transform: (value) => {
          return {
            beginTime: value ? moment(value[0]).format('YYYY-MM-DD') : undefined,
            endTime: value ? moment(value[1]).format('YYYY-MM-DD') : undefined,
          };
        }
      }
    },
    {
      title: "商品id/名称",
      dataIndex: "goodsKeyWord",
      key: "goodsKeyWord",
      hideInTable: true,
      fieldProps: {
        placeholder: "请输入商品id/名称"
      }
    },
    {
      title: "日期",
      dataIndex: "createDate",
      key: "createDate",
      width: 150,
      hideInSearch: true
    },
    {
      title: "商品id",
      dataIndex: "goodsId",
      key: "goodsId",
      width: 200,
      hideInSearch: true
    },
    {
      title: "商品名称",
      dataIndex: "goodsName",
      key: "goodsName",
      width: 150,
      hideInSearch: true
    },
    {
      title: "列表页点击人数",
      dataIndex: "listClickCount",
      key: "listClickCount",
      hideInSearch: true,
      width: 180,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日在拼团频道列表页点击该商品的人数（不包括通过搜索、推荐列表页点击的人数），根据手机号、设备id去重
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "列表页点击次数",
      dataIndex: "listClickSum",
      key: "listClickSum",
      hideInSearch: true,
      width: 180,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日在拼团频道列表页点击该商品的次数（不包括通过搜索、推荐列表页点击的次数）
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "拼团发起人数",
      dataIndex: "newTeamCount",
      key: "newTeamCount",
      hideInSearch: true,
      width: 180,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日该商品拼团任务发起的人数之和，根据手机号去重
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "拼团发起次数",
      dataIndex: "newTeamSum",
      key: "newTeamSum",
      width: 180,
      hideInSearch: true,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日该商品拼团任务发起的次数之和（团长的支付时间在当天）
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "裂变注册人数",
      dataIndex: "registerCount",
      key: "registerCount",
      width: 180,
      hideInSearch: true,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日通过该商品拼团任务分享后进入小程序，并完成注册的人数之和（注册时间在当天）
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "成团人数",
      dataIndex: "teamSuccessCount",
      key: "teamSuccessCount",
      width: 180,
      hideInSearch: true,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              参加该商品的拼团活动且当日成团的人数（已成团时间为准，不考虑后续的退款，根据用户id去重）
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "退单人数",
      dataIndex: "refundCount",
      key: "refundCount",
      width: 180,
      hideInSearch: true,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日完成对该商品的拼团活动退款的人数，根据用户id去重（以退款完成时间为准，不包括未成团自动退款的用户）；
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "付款金额",
      dataIndex: "payPrice",
      key: "payPrice",
      width: 180,
      hideInSearch: true,
      filterDropdown: true,
      render: (text) => {
        return '￥' + text
      },
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日参加该商品的拼团活动并完成付款的实付金额之和，不考虑后续的退款金额；保留2位有效数字
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "退款金额",
      dataIndex: "refundPrice",
      key: "refundPrice",
      width: 180,
      hideInSearch: true,
      filterDropdown: true,
      render: (text) => {
        return '￥' + text
      },
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              当日完成对该商品的拼团活动退款的金额之和（以退款完成时间为准）；保留2位有效数字
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
    },
    {
      title: "退款率",
      dataIndex: "refundRate",
      key: "refundRate",
      width: 180,
      hideInSearch: true,
      filterDropdown: true,
      filterIcon: () => {
        return (
          <Tooltip zIndex={999} placement="top" title={() => {
            return <div>
              退单率=退单人数/成团人数，保留2位有效数字
            </div>
          }}  >
            <QuestionCircleOutlined />
          </Tooltip>
        );
      },
      render: (text, record) => {
        return record.refundRate > 0 ? record.refundRate * 100 + "%" : 0 + "%"
      }
    },
  ]
  const toExport = async () => {
    setExportLoading(true)
    await apiExportDataDashboards({ activityId: queryForm.activityId, beginTime: queryForm.beginTime, endTime: queryForm.endTime, goodsKeyWord: queryForm.goodsKeyWord }).then(res => {
      if (res.code === 0 && res.data) {
        let tb_arr = []
        res.data.map(res => {
          res.refundRate = res.refundRate * 100 + "%"
        })
        tb_arr = res.data
        const option = {
          fileName: '拼团',
          header: [
            {
              title: '拼团',
              prop: '',
              children: [
                {
                  title: '日期',
                  prop: 'createDate',
                },
                {
                  title: '商品id',
                  prop: 'goodsId',
                },
                {
                  title: '商品名称',
                  prop: 'goodsName',
                },
                {
                  title: '列表页点击人数',
                  prop: 'listClickCount',
                  valueType: 'number'
                },
                {
                  title: '列表页点击次数',
                  prop: 'listClickSum',
                },
                {
                  title: '拼团发起人数',
                  prop: 'newTeamCount',
                },
                {
                  title: '拼团发起次数',
                  prop: 'newTeamSum',
                },
                {
                  title: '裂变注册人数',
                  prop: 'registerCount',
                },
                {
                  title: '成团人数',
                  prop: 'teamSuccessCount',
                },
                {
                  title: '退单人数',
                  prop: 'refundCount',
                },
                {
                  title: '付款金额',
                  prop: 'payPrice',
                },
                {
                  title: '退款金额',
                  prop: 'refundPrice',
                },
                {
                  title: '退款率',
                  prop: 'refundRate',
                },
              ]
            },
          ],
          dataSource: tb_arr
        }
        Json2Excel(option)
      }
    })
  }
  return <div>
    <GoBack title={"查看"} />
    <ProTable
      actionRef={actionRef}
      scroll={{ x: 900, y: '57vh' }}
      rowKey={(record) => record.memberId}
      bordered={true}
      options={false}
      columns={columns}
      pagination={{
        defaultPageSize: 10,
        position: ['bottomCenter'],
        showSizeChanger: false
      }}
      headerTitle={<TheButton key="export" onClick={() => toExport()}>导出</TheButton>}
      params={{
        activityId: location.state.activityId
      }}
      request={async (params, sort, filter) => {
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        const res = await apiGetSpellTogetherDashboards({
          pageNo: params.current,
          pageSize: params.pageSize,
          ...params
        });
        setQueryForm(params)
        return {
          data: res.data,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: res.code === 0,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: res.totalCount,
        };
      }}
      search={{
        optionRender: (searchConfig, formProps, dom) => {
          return dom.reverse()
        },
        collapsed: false,
        collapseRender: false
      }}
    />
  </div>
}
